package com.fly.hbn.controller;

import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.pool.DruidDataSource;
import com.fly.hbn.model.Customer;
import com.fly.hbn.service.CustomerService;

@Controller
public class CustomerController
{
    @Autowired
    CustomerService customerService;
    
    @Autowired
    DruidDataSource dataSource;
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("customer") Customer customer)
    {
        if (customer.getId() == 0)
        {
            customerService.addCustomer(customer);
        }
        else
        {
            customerService.updateCustomer(customer);
        }
        return "redirect:/list";
    }
    
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") int id)
    {
        customerService.deleteCustomer(id);
        return "redirect:/list";
    }
    
    @ResponseBody
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public Customer get(@PathVariable int id)
    {
        return customerService.getCustomer(id);
    }
    
    @RequestMapping(value = {"/", "/list"}, method = RequestMethod.GET)
    public String list(Model model)
    {
        List<Customer> listOfCustomers = customerService.getAllCustomers();
        model.addAttribute("item", new Customer("customer" + RandomStringUtils.randomNumeric(3), RandomStringUtils.randomAlphanumeric(10)));
        model.addAttribute("list", listOfCustomers);
        model.addAttribute("jdbcUrl", dataSource.getRawJdbcUrl());
        return "show";
    }
    
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") int id, Model model)
    {
        model.addAttribute("item", this.customerService.getCustomer(id));
        model.addAttribute("list", this.customerService.getAllCustomers());
        return "show";
    }
}
